package com.lambkit.core.flow;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.File;
import java.nio.charset.Charset;

/**
 * @author yangyong(孤竹行)
 */
public class FlowJsonBuilder implements IFlowBuilder {

    private FlowObject flowObject;
    private String jsonFile;

    public FlowJsonBuilder(String jsonFile) {
        this.jsonFile = jsonFile;
        readFlowObjectFromFile(jsonFile);
    }

    public FlowJsonBuilder(String jsonFile, FlowObject flowObject) {
        this.jsonFile = jsonFile;
        this.flowObject = flowObject;
    }

    public FlowJsonBuilder(String jsonFile, String json) {
        this.jsonFile = jsonFile;
        readFlowObjectFromJson(json);
    }

    private void readFlowObjectFromFile(String jsonFile) {
        String json = ResourceUtil.readUtf8Str(jsonFile);
        readFlowObjectFromJson(json);
    }

    private void readFlowObjectFromJson(String json) {
        if(StrUtil.isNotBlank(json)) {
            JSONObject jsonFlow = JSONUtil.parseObj(json);
            this.flowObject = jsonFlow.toBean(FlowObject.class);
        } else {
            this.flowObject = new FlowObject();
            this.flowObject.setCode(IdUtil.simpleUUID());
        }
    }

    @Override
    public FlowObject getFlow() {
        return flowObject;
    }

    @Override
    public void saveFlow() {
        if (flowObject != null) {
            String flowId = flowObject.getCode();
            File file = new File(jsonFile);
            String json = JSONUtil.toJsonPrettyStr(flowObject);
            FileUtil.writeString(json, file, Charset.forName("UTF-8"));
        }
    }
}
